package com.fang;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * 测试事务
 * @author 川川
 * @date 2021/9/25 17:38
 */
public class TestTx {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.183.128", 6379);
        jedis.auth("123456");
        System.out.println(jedis.ping());
        // 清空数据库
        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "xinchao");
        String result = jsonObject.toString();

        // 开启事务
        Transaction multi = jedis.multi();
        try {
            // 命令入队
            multi.set("user1", result);
            int i = 1/0; // 发生运行时异常
            multi.set("user2", result);

            // 执行事务
            multi.exec();
        } catch (Exception e) {
            multi.discard();// 放弃事务
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }
    }
}
